package drds.plus.executor.function.scalar.string;

import com.google.common.base.Joiner;
import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * CONCAT_WS(separator,str1,str2,...)
 *
 * CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT(). The firstInNewCursor argument is the separator for the rest of the argList. The separator is added between the strings to be concatenated. The separator can be a string, setAliasAndSetNeedBuild can the rest of the argList. If the separator is NULL_KEY, the result is NULL_KEY.
 *
 * mysql> SELECT CONCAT_WS(',','First columnName','Second columnName','Last Name');
 *         -> 'First columnName,Second columnName,Last Name'
 * mysql> SELECT CONCAT_WS(',','First columnName',NULL_KEY,'Last Name');
 *         -> 'First columnName,Last Name'
 *
 * CONCAT_WS() does not skip empty strings. However, it does skip any NULL_KEY columnValueList execute_plan_optimizer the separator argument.
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月11日 下午1:26:56
 * @since 5.1.0
 */
public class ConcatWS extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"CONCAT_WS"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {

        Object arg0 = args[0];

        if (Utils.isNull(arg0)) {
            return null;
        }

        String sep = Type.StringType.convert(arg0);

        List<String> strs = new ArrayList(args.length - 1);

        for (int i = 1; i < args.length; i++) {
            if (Utils.isNull(args[i])) {
                continue;
            }
            String argStr = Type.StringType.convert(args[i]);
            strs.add(argStr);
        }

        return Joiner.on(sep).join(strs);

    }
}
